package com.wanger.swa.convert;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wanger.swa.domain.myEnum.DataSourceEnum;
import com.wanger.swa.dto.dataSource.inf.DataSourceDispatch;
import com.wanger.swa.dto.dataSource.req.DataSourceAddReq;
import com.wanger.swa.dto.dataSource.req.DataSourceUpdateReq;
import com.wanger.swa.dto.dataSource.resp.DataSourceResp;
import com.wanger.swa.domain.po.DataSourcePO;
import com.wanger.swc.config.dataInstance.model.DataInstanceType;
import org.anyline.metadata.type.DatabaseType;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author: wanger
 * @Date: 2024/9/16 17:40
 * @Description: 数据源
 */
@Component
public class DataSourceConvert {
    @Resource
    private DataSourceDispatch dataSourceDispatch;

    public DataSourcePO toSaveEntity(DataSourceAddReq addDTO) {
        DataSourcePO po = BeanUtil.copyProperties(addDTO, DataSourcePO.class);
        dataSourceDispatch.verify(po);
        return po;
    }

    public DataSourcePO toUpdateEntity(DataSourceUpdateReq updateDTO) {
        DataSourcePO po = BeanUtil.copyProperties(updateDTO, DataSourcePO.class);
        dataSourceDispatch.verify(po);
        return po;
    }

    public DataSourceResp toDetailsDTO(DataSourcePO dataSource) {
        return toListDTO(CollUtil.toList(dataSource))
                .stream()
                .findFirst()
                .orElse(null);
    }

    public List<DataSourceResp> toListDTO(List<DataSourcePO> list) {
        List<DataSourceResp> dtoList = BeanUtil.copyToList(list, DataSourceResp.class);
        for (DataSourceResp dto : dtoList) {
            dto.setTypeName(DataSourceEnum.getEnumName(dto::getType));
            switch (DataSourceEnum.getEnumByFieldAndCode(dto::getType)) {
                case STRUCTURE: {
                    dto.setContentTypeName(DatabaseType.valueOf(dto.getContentType()).title());
                    break;
                }
                case INSTANCE: {
                    dto.setContentTypeName(DataInstanceType.getByType(dto.getContentType()).getDesc());
                    break;
                }
            }

        }
        return dtoList;
    }

    public IPage<DataSourceResp> toPageDTO(IPage<DataSourcePO> page) {
        return new Page<DataSourceResp>()
                .setRecords(toListDTO(page.getRecords()))
                .setTotal(page.getTotal())
                .setSize(page.getSize())
                .setCurrent(page.getCurrent())
                .setPages(page.getPages());
    }
}
